package com.ghaoxiang.servicehi;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.logging.Level;
import java.util.logging.Logger;

import brave.Tracer;
import brave.propagation.CurrentTraceContext;
import brave.sampler.Sampler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@RestController
public class ServiceHiApplication {

	public static void main(String[] args) {
		SpringApplication.run(ServiceHiApplication.class, args);
	}

	private static final Logger LOG = Logger.getLogger(ServiceHiApplication.class.getName());
	static ExecutorService executor = Executors.newFixedThreadPool(3);

	@Autowired
	private RestTemplate restTemplate;
//	@Autowired
//	Tracer tracer;

	@Bean
	public RestTemplate getRestTemplate(){
		return new RestTemplate();
	}

	@RequestMapping("/hi")
	public String callHome()throws Exception{
		LOG.log(Level.INFO, "calling trace service-hi  ");
//		System.out.println(tracer.currentSpan().context().traceId());
		System.out.println(CurrentTraceContext.Default.inheritable().get().traceId());

		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				restTemplate.getForObject("http://localhost:8989/miya", String.class);
			}
		});
		CurrentTraceContext.Default.inheritable().executorService(executor).execute(thread);
		Thread.currentThread().sleep(2000);
		return "xx1";
	}

	@RequestMapping("/info")
	public String info(){
		System.out.println(CurrentTraceContext.Default.inheritable().get().traceId());

		LOG.log(Level.INFO, "calling trace service-hi ");
		return "i'm service-hi";
	}

	@Bean
	public Sampler defaultSampler() {
		return Sampler.ALWAYS_SAMPLE;
	}
}

